package com.d3works.csv.script;

import com.d3works.apps.sale.service.configurator.ConfiguratorCreatorImportService;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.meta.MetaScanner;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

public class ImportConfiguratorCreator {

  @Inject ConfiguratorCreatorImportService configuratorCreatorImportService;

  @Transactional
  public Object importConfiguratorCreator(Object bean, Map values)
      throws D3worksException, IOException {
    String path = String.valueOf(values.get("path"));
    File dataFile = new File(path);
    URL url =
        MetaScanner.findAll("d3works-production", dataFile.getParent(), dataFile.getName()).stream()
            .findAny()
            .orElseThrow(
                () ->
                    new D3worksException(
                        TraceBackRepository.CATEGORY_INCONSISTENCY,
                        "Error when importing configurator creators demo data."));
    configuratorCreatorImportService.importConfiguratorCreators(url.openStream());
    return null;
  }
}
